<template>
<!-- 类目 -->
  <div id="Administration">
    <div id="managements">
      <!--搜索框 -->
      <div id="manage-top">
        <el-input placeholder="请输入类目ID" v-model="allPages.value"></el-input>
        <el-input placeholder="请输入类目名称" v-model="allPages.label"></el-input>
        <el-select v-model="allPages.level" clearable placeholder="请选择类目等级">
          <el-option
            style="height:46px"
            v-for="item in levelLabel"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-cascader v-model="input" :props="{ checkStrictly: true,value:'value',label:'label' }" :options="spuTitl" @change="list" ref="cascader" placeholder="请选择父类目"></el-cascader>            
        <button type="button" class="el-button el-button--primary" @click="management()">
          <i class="el-icon-search"></i>
          <span>查找</span>
        </button>
        <button type="button" class="el-button el-button--primary" @click="additions()" v-Promise="'operation:category:create'">
            <i class="el-icon-edit"></i><span>添加</span>
        </button>
      </div>
      <!-- 数据操作 -->
      <div id="manage-bottom">
        <el-table
          border
          :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
          :key="id"
        >
          <el-table-column label="类目ID" prop="value"></el-table-column>
          <el-table-column label="类目名" prop="label">
            <template slot-scope="scope">
               <el-tag>{{scope.row.label}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="全类目名" prop="fullName">
            <template slot-scope="scope">
               <el-tag>{{scope.row.fullName}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="父类目ID" prop="parent"></el-table-column>
          <el-table-column label="级别" prop="level">
             <template slot-scope="scope">
               <el-tag>{{scope.row.level|levelTitle()}}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="标志图片" prop="iconUrl"> </el-table-column>
          <el-table-column label="类目图片" prop="picUrl">
            <template slot-scope="scope">
                <img :src="scope.row.picUrl" style="height:50px">
            </template>
          </el-table-column>
          <el-table-column align="right" label="操作" width="250px;">
            <template slot-scope="scope">
              <el-button
                size="mini"
                @click="compile(scope.$index,scope.row)"
                v-Promise="'operation:category:update'"
                class="kohlrabiblue"
              >编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.$index,scope.row)" v-Promise="'operation:category:delete'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div id="block">
        <!-- current-change当前页size-change每页条数current-page当前页数，支持 .sync 修饰符page-sizes每页显示条目个数，支持 .sync 修饰符-->
        <Paging @handle="handles" :allPages="allPages"></Paging>
      </div>
      <div>
        <!-- 添加编辑弹框 -->
        <el-dialog :title="titleName" :visible.sync="dialogFormVisible">
          <div class="loginRight">
            <div class="login-right">
              <el-form
                :model="ruleForm"
                status-icon
                ref="ruleForm"
                :rules="rules"
                label-width="100px"
                class="demo-ruleForm">
                <el-form-item prop="label" label="类目名字">
                   <el-input  v-model="ruleForm.label"></el-input>
                </el-form-item>
                <div class="uploading">
                  <div class="uptitle">
                      <span>类目美图</span>
                    </div>
                    <el-upload
                      class="avatar-uploader"
                      action="http://192.168.1.99:8080/upload/admin"
                      :show-file-list="false"
                      :on-success="handleAvatarSuccess"
                      :before-upload="beforeAvatarUpload">
                      <img v-if="imageUrl" :src="imageUrl" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </div>
                <!-- 父类目 -->
                <el-form-item prop="min" label="父类目">
                   <el-cascader v-model="ruleForm.parentId" :props="{ checkStrictly: true,value:'value',label:'label' }" @change="list" ref="cascader" :options="spuTitl" placeholder="请选择父类目,默认一级类目"></el-cascader>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="affirm()">
              <div>确 定</div>
            </el-button>
          </div>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script>
import category from "@/api/category.js";
import Paging from "../../components/Paging"; //分页
import qs from "qs";
export default {
  components: {
    Paging
  },
  data() {
    return {
      forbidden:false,
      spuTitl: [],
      imageUrl:'',
      levelLabel: [
        {
          value: 0,
          label: "一级类目"
        },
        {
          value: 1,
          label: "二级类目"
        },
        {
          value: 2,
          label: "三级类目"
        }
      ],
      rules:{
        label:[
          { required: true, message: '类目名字不能为空！', trigger: 'blur' },
        ]
      },
      id: "",
      input: "",
      search: "",
      titleName: "", //是否添加还是编辑
      tableData: [{}],
      dialogFormVisible: false, //弹窗口
      allPages: {
        currentPage: 1, //当前的默认的页数
        eachpage: 20, //默认的页码
        total: 0, //初始值共数据条
        totalPageNo: 1,
        // 查询      
         value:'',
         label:'',
         level:'',
         parentId: ""
      }, //分页
      ruleForm: {
        title:'',
        parentId:'',
        level:'',
        value:'',
        label:"",
        parent:''
      },
    };
  },
  filters: {
    levelTitle:function(value){
      switch (value) {
        case 0:return value='一级类目'        
         break;
         case 1:return value='二级类目'        
         break;
         case 2:return value='三级类目'        
         break;
      }
    }
  },
  methods: {
    //上传图片
      handleAvatarSuccess(res, file) {
        console.log(res)
        this.imageUrl = URL.createObjectURL(file.raw);
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
    // 编辑
    compile(index, row) {
      console.log(row)
      this.forbidden=true
      this.dialogFormVisible = true;
      this.titleName = "编辑";
      this.modalType = "update";
      this.ruleForm = {...row}
      this.imageUrl=row.picUrl
      this.ruleForm.label=row.label
      this.ruleForm.parentId=row.parent    
    },
    //添加
    additions() {
      this.forbidden=false
      this.titleName = "创建";
      this.modalType = "add";
      this.dialogFormVisible = true;
      this.ruleForm={}
      this.imageUrl=""
    },
    // 分页负值
    handles(val) {
      this.allPages = val;
      this.management();
    },
    // 管理员数据列表
    management() {
      let _this = this;
      category.categoryList(_this.allPages,_this.ruleForm).then(function(res) {
        console.log(res.data);
        _this.tableData = res.data.data.items;
        // 分页
        _this.allPages.currentPage = res.data.data.pageNo;
        _this.allPages.eachpage = res.data.data.pageSize;
        _this.allPages.total = res.data.data.total;
        _this.allPages.totalPageNo = res.data.data.totalPageNo;
      });
    },
      // 递归
      getTreeData(data){
      for(var i=0;i<data.length;i++){
        if(data[i].children.length<1){
          // children若为空数组，则将children设为undefined
          data[i].children=undefined;
        }else {
          if (data[i].children.length==3) {
             data[i].children=undefined;
          }else{
             // children若不为空数组，则继续 递归调用 本方法
              this.getTreeData(data[i].children);
          }
         
        }
      }
      return data;
    },
    // sup树
    supshu() {
        let _this=this;
      category.tree().then(res => {
        console.log(res)
        _this.spuTitl =_this.getTreeData(res.data.data);
      });
    },
   affirm(){
     let _this=this;
     if (_this.titleName=="创建") {
       let data={
         title:_this.ruleForm.label,
         parentId:_this.ruleForm.value,
         picUrl:_this.imageUrl,
         level:_this.ruleForm.level,
       }       
        category.addition(data).then(res => {
         if (res.data.errno==200) {
            _this.$information.success('添加成功')
             _this.management()
           _this.dialogFormVisible = false;

         }        
      });
     }
     if (_this.titleName=="编辑") {
       let data={
         title:_this.ruleForm.label,
         parentId:_this.ruleForm.parentId,
         picUrl:_this.imageUrl,
         level:_this.ruleForm.level,
         id:_this.ruleForm.value
       }      
       console.log(data)   
        category.compile(data).then(res => {
          console.log(res)
         if (res.data.errno==200) {
            _this.$information.success('编辑成功')
             _this.management()
           _this.dialogFormVisible = false;
         }
      });
     } 
   },
   list(value){
        this.ruleForm.parentId=value[value.length-1]  //获取级联id  
     },
    // 删除
        handleDelete(index,row) {
          var _this = this;
           //   提示框
          _this.$confirm("此操作将永久删除该类目---"+row.label+"---, 是否继续?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            })
            .then(() => {
              _this.$information.success('删除成功')
              let data={
                id:row.value
              }              
              category.delete(data).then(function(res) {
                 _this.tableData.splice(index, 1);
              });
            });
        },
  },
  created() {
    this.management();
    this.supshu(); //sup树
  },
   watch:{
    dialogFormVisible(value){
      if(value==false){
         this.ruleForm.parentId=''
      }
      this.$nextTick(() => {
       this.$refs.ruleForm.clearValidate();
      })
    }
  }
};
</script>

<style scoped>
#Administration {
  width: 100%;
  height: 100%;
}
#Administration ::-webkit-scrollbar {
  width: 0px !important;
}
#managements {
  width: 80vw;
  height: 80vh;
  margin: auto;
}
/* 搜索框 */
#manage-top {
  width: 100vw;
  display: flex;
  margin-bottom: 30px;
}
#manage-top .el-input__inner {
  width: 200px;
}
.el-input {
  width: 210px;
}

/* 表格样式*/
#block {
  margin-top: 30px;
}
.kohlrabiblue {
  background: #66b1ff;
  color: #ffffff;
}
.el-table--enable-row-transition/deep/.el-table__body td {
  text-align: center;
}
.el-table/deep/th.is-sortable {
  cursor: pointer;
  text-align: center;
}
.el-table td,
.el-table/deep/th.is-leaf {
  text-align: center;
}
/* 弹出框 */
.el-input-group__append {
  position: relative;
  top: -40px;
  left: 210px;
}
#deadline {
  position: relative;
}
.time {
  position: absolute;
  top: 42px;
  left: 0px;
}
.el-form-item__content {
    height: 10px;
}
/* 上传图片 */
/*  */
.loginRight {
  width: 100%;
  height: 100%;
  background: #ffffff;
  border-radius: 0px 8px 8px 0px;
}
.login-right {
  width: 80%;
  margin: auto;
}
.loginRight .login-title {
  color: #333;
  margin-bottom: 40px;
  font-weight: 500;
  font-size: 22px;
  text-align: center;
  letter-spacing: 4px;
  margin-top: 40px;
}
.el-form-item/deep/input {
  background: transparent;
  border-radius: 0;
  color: #333;
  display: inline;
}
.el-form-item {
  height: 50px !important;
  position: relative;
}
.el-form-item/deep/i {
  display: inline;
}
.impose {
  padding-top: 40px;
  position: relative;
}
.poke {
  position: absolute;
  top: 55px;
  left: -102px;
}
.el-checkbox {
   border-color: #409EFF;
  width: 300px;
  margin: 20px 0px 30px 0px;
}
.avatar-uploader .el-upload {
    border: 1px dashed #409EFF;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #409EFF;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.uploading{
    margin-left:25px;
    margin-bottom: 20px;
  }
  .uploading span{
    height: 0px ;
    color: #606266;
  }
  .avatar-uploader{
    margin-left:100px;
  }
  .uptitle{
    height: 0px;
  }
</style>